package com.sweetguy.component;

import cn.hutool.json.JSONUtil;
import com.sweetguy.result.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.sweetguy.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //
        return true;
    }

    //把返回值封装成json串
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //如果是字符串类型转成json串
        if (aClass == StringHttpMessageConverter.class) {
            return JSONUtil.toJsonStr(o);
        }

        //返回json串
        if (o instanceof Result) {
            return o;
        }

        //不是字符串类型通过Result转成json串
        return new Result<>(o);
    }
}
